package com.hdg.boot.excel_listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.hdg.boot.bo.XirMdBo;
import com.hdg.boot.service.DataCompareService;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.annotation.Resource;
import java.util.List;

public class DataComparisonListener implements ReadListener<XirMdBo> {

    private static final Logger logger= LoggerFactory.getLogger(DataComparisonListener.class);

    /**
     * 每隔500条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 500;
    /**
     * 缓存的数据
     */
    private List<XirMdBo> list = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private final String tableName;
    @Resource
    DataCompareService dataCompareService;

    /**
     * @param dataCompareService
     */
    public DataComparisonListener(DataCompareService dataCompareService, String tableName) {
        this.dataCompareService = dataCompareService;
        this.tableName = tableName;
    }

    @SneakyThrows
    @Override
    public void invoke(XirMdBo xirMdBo, AnalysisContext analysisContext) {
        logger.info("解析到一条数据:{}", JSON.toJSONString(xirMdBo));
        list.add(xirMdBo);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @SneakyThrows
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        //处理准生产缓解比测速环境多的表和字段
        hadTableAndColumn();
        logger.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData(){
        if (list.size() == 0){
            logger.error("对比数据为空！");
            return;
        }
        dataCompareService.addXirMdsByName(list,tableName);
    }

    /**
     * 将准生产环境中多的表及字段添加至对比表中
     */
    private void hadTableAndColumn() {
        dataCompareService.hadTableAndColumn(tableName);
    }
}
